# -*- coding: utf-8 -*-

'''
This file is a textobot App HTTP Capture plugin.
'''

import os
import codecs
import urllib2
import time
import subprocess
import json
import frida

# our textobotee
target_bid = 'com.apple.AppStore'

# this plugin package's root directory
pkg_root = os.path.dirname(__file__)

# pickup this plugin's version dynamically
with open(pkg_root + '/textobot.json', 'r') as fp:
    pkginfo = json.load(fp)
    pkg_version = pkginfo['version']

# frida device
idev = frida.get_remote_device()

# handler for our textobot.js message
def on_frida_message(message, data):
    print(message)

def post_javascript(pid, jscode):
    # attach to target
    session = idev.attach(pid)
    if not session:
        print("Oops, what's wrong with attaching for %s %s." % (bid, pid))
        return
    # create script session
    script = session.create_script(jscode)
    # fire to run the javascript code
    script.on('message', on_frida_message)
    script.load()

# fire javascript to target app
def fire_javascript(bid, pid):
    # only attach our textobotee
    if bid == target_bid:
        # pickup this plugin's javascript code dynamically
        with codecs.open(pkg_root + '/textobot.js', 'r', 'utf-8') as fp:
            jscode = fp.read()
            post_javascript(int(pid), jscode)

# handler for event
def TB_on_event(dictarg):
    return {}

# run an app
def run_app(bid):
    print('start app : %s' % (bid))
    TB_launch(bid)

# run a shell command
def run_cmd(s):
    print('run cmd : %s' % (s))
    subprocess.Popen(s, shell=True).wait()

# handler for main
def TB_main(dictarg):
    event = dictarg['event']
    if event == 'install':
        print('Installed Httpeek plugin for ' + target_bid)
        # codesign for our native library
        run_cmd('ldid -S %s/httpeek.so' % (pkg_root))
    elif event == 'start':
        print('Start Httpeek plugin for ' + target_bid)
        run_app(target_bid)
    elif event == 'apprun':
        print('Httpeek ' + dictarg['name'] + ' is running')
        fire_javascript(dictarg['name'], dictarg['pid'])
    elif event == 'appdie':
        print('Httpeek ' + dictarg['name'] + ' has been died')
    else:
        print('Httpeek plugin event : ' + event)
    return {}

print('the Httpeek plugin(%s) is waiting for event ...' % (pkg_version))
